# -*- coding: utf-8 -*-

# File Name： launch
# Description :
# Author : lirui
# create_date： 2022/9/14
# Change Activity:
import ml
from ml import ConfigLoader
from ml.third_party.csv.xls_utility import read_all_sheet_xls_mapping, write_sheets_mapping
from modules.generate_label.obj.dc import DCContainer


def combine_row_mapping(row_mapping):
    """

    Args:
        row_mapping:

    Returns:

    """
    labels_mapping = []
    board_id_mapping = {}
    for row in row_mapping:
        local_end = row['local_end'].replace('本端：', '')
        opposite_end = row['opposite_end'].replace('对端：', '')
        local_board_id = _get_local_board_id(local_end)
        if local_board_id not in board_id_mapping:
            board_id_mapping[local_board_id] = []
        board_id_mapping[local_board_id].append({'local_end': local_end, 'opposite_end': opposite_end})
    keys = sorted(board_id_mapping.keys())
    for key in keys:
        obj = board_id_mapping[key]
        local_label = '本:'
        opposite_label = '对:'
        for end in obj:
            local_label = local_label + end['local_end'] + '&'
            opposite_label = opposite_label + end['opposite_end'] + '&'
        local_label = local_label[:-1]
        opposite_label = opposite_label[:-1]
        label = local_label + '\n' + opposite_label
        obj.append(label)
        labels_mapping.append({'label': label})
    return labels_mapping


def _get_local_board_id(end_name):
    """

    Args:
        end_name:

    Returns:

    """
    items = end_name.split('.')[:5]
    board_id = '.'.join(items)
    return board_id


def _generate_board_label_excel(board_labels, same_sheet=True):
    """

    Args:
        board_labels:
        same_sheet:

    Returns:

    """
    excel_rows = []
    if same_sheet:
        keys = sorted(board_labels.keys())
        for carbine_name in keys:
            info = board_labels[carbine_name]
            for u, lst in info.items():
                excel_rows = excel_rows + lst
        row_mapping = []
        map1 = {}
        map2 = {}
        for label in excel_rows:
            local_end, opposite_end = label.split('\n')
            row_mapping.append({'label': label, 'local_end': local_end, 'opposite_end': opposite_end})
            map1[local_end.replace('本端：', '').replace('对端：', '')] = opposite_end.replace('本端：', '').replace('对端：', '')
            # map2[opposite_end.replace('本端：', '').replace('对端：', '')] = local_end.replace('本端：', '').replace('对端：', '')
        for k in map1:  # 实现标签一一对应
            v = map1[k]
            if map1[v] != k:
                print(k + ' ' + v)
                print(v + ' ' + map1[v])
                print('----------------------------')
        labels_mapping = combine_row_mapping(row_mapping)
        write_sheets_mapping('board_labels.xls', {'Sheet1': labels_mapping})
    else:
        sheets_mapping = {}
        keys = sorted(board_labels.keys())
        for carbine_name in keys:
            sheets_mapping[carbine_name] = []
            info = board_labels[carbine_name]
            for u, lst in info.items():
                for label in lst:
                    sheets_mapping[carbine_name].append({'label': label})
        write_sheets_mapping('board_labels.xls', sheets_mapping)


def _generate_u_label_excel(u_labels, same_sheet=True):
    cable_rows = []
    cat_rows = []
    if same_sheet:
        keys = sorted(u_labels.keys())
        for carbine_name in keys:
            info = u_labels[carbine_name]
            for u, lst in info.items():
                for line in lst:
                    if '\n' in line:
                        cable_rows.append(line)
                    else:
                        cat_rows.append(line)
        row_mapping = []
        for label in cable_rows:
            if '\n' in label:
                local_end, opposite_end = label.split('\n')
                local_end = local_end.replace('本端：', '')
                opposite_end = opposite_end.replace('对端：', '')

            else:
                local_end, opposite_end = label.split(' ')
            row_mapping.append({'label': label, 'local_end': local_end, 'opposite_end': opposite_end})
        write_sheets_mapping('cable_u.xls', {'Sheet1': row_mapping})
        row_mapping = []
        for label in cat_rows:
            if '\n' in label:
                local_end, opposite_end = label.split('\n')
            else:
                local_end, opposite_end = label.split(' ')
            row_mapping.append({'label': label, 'local_end': local_end, 'opposite_end': opposite_end})
        write_sheets_mapping('cat_u.xls', {'Sheet1': row_mapping})
    else:
        sheets_mapping = {}
        keys = sorted(u_labels.keys())
        for carbine_name in keys:
            sheets_mapping[carbine_name] = []
            info = u_labels[carbine_name]
            for u, lst in info.items():
                for label in lst:
                    sheets_mapping[carbine_name].append({'label': label})
        write_sheets_mapping('u_labels.xls', sheets_mapping)


def _main():
    """

    """
    mappings = {}
    xls_path_lst = ['resource/富滇银行新大楼-标签-设备位置统计信息_20220908_v1.8.xls',
                    "resource/背视图v1.0.xls"]
    for p in xls_path_lst:
        xls_path = ml.join_relative_path(p)
        ml.logger.info(rf'xls path {xls_path}')
        sheets_mapping = read_all_sheet_xls_mapping(xls_path)
        mappings.update(sheets_mapping)
        mappings = ConfigLoader.merge_a_into_b(sheets_mapping, mappings)
    dc_container = DCContainer(mappings)
    board_labels, u_labels = dc_container.collect_labels()
    local_labels = []
    for _, info in board_labels.items():
        for _, labs in info.items():
            for lab in labs:
                if lab not in local_labels:
                    local_labels.append(lab)
                else:
                    print(lab)
                    # raise Exception(lab)  # 标签已经存在
    _generate_board_label_excel(board_labels, same_sheet=True)
    _generate_u_label_excel(u_labels, same_sheet=True)


if __name__ == '__main__':
    _main()
